package com.java.common.boot.advice;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.java.common.constant.ProjectConstants;
import com.java.common.lang.domain.BaseResult;
import com.java.common.lang.domain.ReturnVO;

/**
 * 统一包装接口响应对象
 * 
 * @author yilabao
 * @date 2021年2月1日
 */
@RestControllerAdvice(basePackages = ProjectConstants.PROJECT_PACKAGE)
public class FormatResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
            ServerHttpResponse response) {

        if (body == null) {
            return body;
        }

        if (!(body instanceof ReturnVO) && !(body instanceof String) && !(body instanceof BaseResult)) {
            return new ReturnVO<>(body);
        }

        return body;
    }

}
